const app = document.getElementById('app');
const login_div = document.getElementById('login');
const files_div = document.getElementById('files');
const content_div = document.getElementById('content');
const index_div = document.getElementById('index');
const left = document.getElementById('left');
const login_submit = document.getElementById('login_submit');

// 当前路径
var cur_path = '';
// 是否是登录页
var is_login_page = false;

/// 启动时检查
window.onload = async function () {
        await read_config();
        const token = get_token();
        if (!token) {
                display_login();
                return;
        }
        await load_menu();
}

/// 登录提交绑定事件
login_submit.onclick = async function () {
        await login();
}

document.onkeydown = async function (e) {
        if (e && (e.key == 'Enter' || e.key == 'NumpadEnter') && is_login_page) {
                await login();
        }
}

async function login () {
        const usr = document.getElementById('account');
        const pwd = document.getElementById('password');
        if (!usr.value || !pwd.value) {
                toast('失去登录信息', 1);
                return;
        }
        let rsp = await note_request('/user/login', { usr: usr.value, pwd: pwd.value });
        deal_res(rsp, async function (data) {
                set_token(data);
                await load_menu();
        });
}

async function to_index () {
        display_index();
        cur_path = '';
}

function to_exit () {
        cur_path = '';
        history.back();
}

async function to_return () {
        const path_res = await note_request('/file/load-parent', { path: cur_path });
        deal_res(path_res, function (files) {
                display_files();
                // 将过来的数据显示到右侧，渲染
                combine_file(files);
                cur_path = last_path(cur_path);
        });
}

/// 加载菜单
async function load_menu () {
        is_login_page = false;
        cur_path = '';
        display_index();
        // 处理菜单数据
        const menu_rsp = await note_request('/file/load-menu');
        deal_res(menu_rsp, function (menu_data) {
                for (let k in menu_data) {
                        // 组合菜单
                        combine_menu(k, menu_data[k]);
                }
        });
}

/// 给菜单添加点击事件(加载文件列表)
function click_on_menu (item, path) {
        if (!item) return;
        item.onclick = async function () {
                const path_res = await note_request('/file/load-path', { path });
                deal_res(path_res, function (files) {
                        display_files();
                        // 将过来的数据显示到右侧，渲染
                        combine_file(files);
                });
        }
}

function load_list (id, path) {
        let item = document.getElementById(id);
        click_on_menu(item, path);
        cur_path = path;
}

const parser = new DOMParser();

/// 组装file
async function combine_file (files) {
        if (!Array.isArray(files)) {
                console.error('combine_file数据异常');
                await toast('数据异常', 1);
                return;
        }
        files_div.innerHTML = '';
        const random = random_str();
        for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const suffix = `_${random}_${file.name}`;
                let file_img;
                let file_alt;
                if (file.file_type == 'File') {
                        file_img = '../img/file.svg';
                        file_alt = '文件';
                } else {
                        file_alt = '文件夹';
                        file_img = '../img/folder.svg';
                }
                const size = mem2readable(file.size);
                let res = `
                        <div id="file${suffix}" class="files-item">
                                <div id="file_left${suffix}" style="margin-right: 10px">
                                        <img src="${file_img}" alt="${file_alt}" height="50px" width="50px"/>
                                </div>
                                <div id="file_center${suffix}" style="display: flex; justify-content: center; flex-direction: column; position: relative; width: -webkit-fill-available;">
                                        <div><font color="black">${file.name}</font></div>
                                        <div><font color="grey">${size}</font></div>
                                </div>
                `;
                if (file.file_type == 'File') {
                        res += `
                        <div id="file_right${suffix}" style="display: flex; justify-content: center; flex-direction: column; position: relative; width: 10%;">
                                <button onclick="load_file('${file.path}', '${file.name}')">显示</button>
                        `;
                } else {
                        // 同load_menu方法，但显示在右侧
                        res += `
                        <div id="file_right${suffix}" style="display: flex; justify-content: center; flex-direction: column; position: relative; width: 10%;">
                                <button onclick="load_list('file_right${suffix}', '${file.path}${file.name}')">进入</button>
                        `;
                }
                res += `</div></div>`;
                if (i < files.length - 1) {
                        res += `<div class="horizontal-bar"></div>`;
                }
                const node = parser.parseFromString(res, 'text/html').getElementById(`file${suffix}`);
                files_div.appendChild(node);
        }
}

/// 读取文件
async function load_file (path, name) {
        const file_rsp = await note_request('/file/load-file', { path, name }, 'POST');
        deal_res(file_rsp, function (file_data) {
                display_content();
                // 显示文件数据
                content_div.innerText = file_data;
                cur_path = path + name;
        });
}

/// 组装菜单
/// k: 菜单id
/// v: 菜单值
function combine_menu (k, v) {
        if (!k || !v) {
                console.error('combine_menu数据异常');
                return;
        }
        const random = random_str();
        const id = random + '-' + k;
        const res = `
                <button class="left-btn" id="${id}">${v}</button>
        `;
        const doc = parser.parseFromString(res, 'text/html');
        const m = doc.getElementById(id);
        // 给菜单添加点击事件
        click_on_menu(m, v);
        left.appendChild(m);
}

const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
/// 生成len长度的随机字符
function random_str (len) {
        len = len || 10;
        //默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
        let maxPos = $chars.length;
        let pwd = '';
        for (i = 0; i < len; i++) {
                pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
}

/// 显示登录页
function display_login () {
        is_login_page = true;
        index_div.style = "display:none;";
        files_div.style = "display:none;";
        content_div.style = "display:none;";
        login_div.style = `
                        display:flex;
                        justify-content: center;
                        align-items: center;
                        position: relative;
                        flex-direction: column;
                `;
}

/// 显示index
function display_index () {
        login_div.style = "display:none;";
        files_div.style = "display:none;";
        content_div.style = "display:none;";
        index_div.style = `
                        display:flex;
                        justify-content: center;
                        align-items: center;
                        position: relative;
                        flex-direction: column;
                `;
}

/// 显示content
function display_content () {
        login_div.style = "display:none;";
        files_div.style = "display:none;";
        index_div.style = "display:none;";
        content_div.style = `
                        display:flex;
                        justify-content: center;
                        align-items: center;
                        position: relative;
                        flex-direction: column;
                        word-wrap: break-word;
                        width: 90%;
                `;
}

/// 显示文件列表
function display_files () {
        login_div.style = "display: none;";
        content_div.style = "display: none;";
        index_div.style = "display: none;";
        files_div.style = `
                display:flex;
                align-items: center;
                position: relative;
                flex-direction: column;
        `;
}

/**
 * 结果处理
 * @param {*} rsp 结果
 * @param {*} suc_fun 成功时处理方法
 */
function deal_res (rsp, suc_fun) {
        if (!rsp) {
                console.error('rsp is empty');
                return;
        }
        if (rsp.status == 200) {
                if (rsp.data.code == 0) {
                        suc_fun(rsp.data.data);
                } else {
                        toast(rsp.data.msg, 1);
                }
        } else {
                console.debug('rsp=%O', rsp);
                if (rsp.status == 401) {
                        display_login();
                }
        }
}

// app.innerHTML = `
// `;
// const add_btn = document.getElementById('add_btn');

// const add_view = document.getElementById('add_view');
// add_btn.onclick = async function () {
//         const count = await invoke('counter_add', { n: 3 });
//         add_view.innerText = count;
// };
invoke('hello_test').then((rsp) => {
        console.debug(rsp);
});


// left.onclick = async function () {
//         let rsp = await note_request('/file/load-menu');
// }

// const test1 = document.getElementById('test1');
// test1.onclick = async function () {
//         const yes = await dialog.ask('ask', 'wqe');
// }

// const test2 = document.getElementById('test2');
// test2.onclick = async function () {
//         const yes = await dialog.confirm('confirm', { title: 'Tauri', type: 'error' });
// }

// const test3 = document.getElementById('test3');
// test3.onclick = async function () {
//         const yes = await dialog.message('message', 'wqe');
// }

// const test4 = document.getElementById('test4');
// test4.onclick = async function () {
//         const yes = await dialog.open({ multiple: true, filters: [{ name: 'imageopen', extensions: ['png', 'jpeg'] }] });
// }

// const test5 = document.getElementById('test5');
// test5.onclick = async function () {
//         const yes = await dialog.save({ multiple: true, filters: [{ name: 'imagesave', extensions: ['png', 'jpeg'] }] });
// }